package com.mypro.common.print;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import com.mypro.common.user.Function;
import com.mypro.common.user.FunctionService;
import com.mypro.common.user.User;
import com.mypro.common.user.UserService;

/**
 * @ClassName: NavTree
 * @Description: 加载权限
 * @author liuxd
 * @date 2013-7-6 上午8:29:43
 * 
 */
public class NavTree {

	@Autowired
	private UserService userService = new UserService();

	@Autowired
	private FunctionService functionService = new FunctionService();

	/**
	 * @Title: getNavTree
	 * @Description: 生成菜单树
	 * @param session
	 * @return
	 * @throws
	 */
	public String getNavTree(HttpSession session) {
		StringBuffer sb = new StringBuffer();
		User loginUser = (User) session.getAttribute("loginUser");
		List<String> functionList = new ArrayList<String>();
		functionList = getFunctionList(loginUser.getFunctions());
		Function function = null;
		for (String functionId : functionList) {
			function = functionService.findById(Integer.parseInt(functionId));
			if (function.getParentId() == 0) {
				// 写一级菜单
				sb.append("<h1 class=\"type\"><a href=\"javascript:void(0)\">"
						+ function.getName() + "</a></h1>");
				sb.append("<div class=\"content\">");
				sb.append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
				sb.append("<tr><td><img src=\"../resources/image/menu_topline.gif\" width=\"182\"height=\"5\" /></td></tr>");
				sb.append("</table>");
				if (function.getHaveChild()) {
					List<Function> childList = functionService
							.findChildById(function.getId());
					if (childList.size() > 0) {
						sb.append("<ul class=\"MM\">");
						for (Function child : childList) {
							if (functionList.contains(String.valueOf(child
									.getId()))) {
								sb.append("<li><a href=\""
										+ (child.getHref() == null
												|| "".equals(child.getHref()
														.toString()) ? ""
												: child.getHref()
														+ "\" target=\"main\">")
										+ child.getName() + "</a></li>");
							}
						}
						sb.append("</ul>");
					}
				}
				sb.append("</div>");
			}
		}
		return sb.toString();
	}

	/**
	 * @Title: getFunctionList
	 * @Description: 将权限转为list集合
	 * @return
	 * @throws
	 */
	private List<String> getFunctionList(String functions) {
		List<String> list = new ArrayList<String>();
		if (functions == null || functions.equals("")) {
			return list;
		}
		for (String id : functions.split(",")) {
			list.add(id);
		}
		return list;
	}
}
